package com.kuiniu.threeframe.client;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

public class DefaultChannelInitializer extends ChannelInitializer<Channel> {
    private Client client;

    public DefaultChannelInitializer(Client client) {
        this.client = client;
    }

    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline p = channel.pipeline();
        p.addLast("ping", new IdleStateHandler(client.getReadTimeout(),
                client.getWriteTimeout(), client.getResendCount() + client.getWriteTimeout(),
                TimeUnit.MILLISECONDS));
        // 将分隔之后的字节数据转换为字符串数据
        p.addLast(new StringDecoder(Charset.forName("GBK")));
        p.addLast(new StringEncoder(Charset.forName("GBK")));
        p.addLast(new NettyClientHandler(client));
    }
}
